package com.hemi.rhet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.hemi.rhet.html.TopicList;
import com.hemi.rhet.util.AppParam;
import com.hemi.rhet.util.ApplicationContext;
import com.hemi.rhet.util.FileUtil;
import com.hemi.rhet.util.HttpUtil;

public class ActivityTopicIssure extends Activity{

	private static final String TAG = ActivityTopicIssure.class.getSimpleName();
	private String issurePostUrl = HttpUtil.buildUrl("/post/issurePost");
	LinearLayout layout = null;
//	InputMethodManager m =null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.topic_new);
		ImageView im = (ImageView)findViewById(R.id.topic_close);
		im.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		Button topic_send = (Button)findViewById(R.id.topic_send);
//		  m=(InputMethodManager) topic_send.getContext().getSystemService(INPUT_METHOD_SERVICE); 
//		m.toggleSoftInput(InputMethodManager.RESULT_UNCHANGED_SHOWN, InputMethodManager.HIDE_NOT_ALWAYS); 
		  layout = (LinearLayout) findViewById(R.id.photo_privew);
		
		
		topic_send.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				EditText content = (EditText)findViewById(R.id.postcontent);
				if((content.getText()==null|| content.getText().toString().equals("")) && (photoPathList==null ||photoPathList.size()==0))
				{
					 Toast.makeText(ActivityTopicIssure.this, "您还没有输入哦 @_@",Toast.LENGTH_SHORT).show();        
					return ;
				}
				params = new HashMap();
				params.put("post.content", content.getText().toString());
				new PostTopic().execute();
			}
		});
	
		
		ImageButton uploadImageButton = (ImageButton)findViewById(R.id.uploadImageButton);
		uploadImageButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
//				Intent i= new Intent();
//				i.setClass(ActivityTopicIssure.this, PhotoUpload.class);
//				startActivityForResult(i,R.id.uploadImageButton);
				select_photo_from_dialog();
			}
		});
	}
	
	
	HashMap params =null;
	private class PostTopic extends AsyncTask<Void, Void, Object> {
	    private ProgressDialog mLoadingDialog;
	    private String issurePostUrl = HttpUtil.buildUrl("/post/issurePost");
	    String imageInfo=null;
	    @Override
	    protected void onPreExecute() {
	    	ApplicationContext.checkLogin(ActivityTopicIssure.this);
	        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
	            mLoadingDialog.setMessage("正在发帖，请稍后...");
	        }else{
	       	 mLoadingDialog = new ProgressDialog(ActivityTopicIssure.this);
	       	 mLoadingDialog.setCancelable(false);
	       	 mLoadingDialog.setMessage("正在发帖，请稍后...");
	         mLoadingDialog.show();
	        }
	    }
	    @Override
	    protected Object doInBackground(Void... ps) {
				   try {
					   if(photoPathList!=null)
						 {
							 for(String photoPath:photoPathList)
						    	{
							    	try {
							    		imageInfo = FileUtil.uploadFile2Server(photoPath);
							    		HashMap mesg = ParamUtil.stringTomsgMap(imageInfo);
										if (mesg.get("resultcode").equals("0")) {
											if(fileIds==null)
									    	{
									    		fileIds=new StringBuffer(""+mesg.get("fileId"));
									    	}else{
									    		fileIds.append(","+mesg.get("fileId"));
									    	}
										}
									} catch (ClientProtocolException e) {
										e.printStackTrace();
										Log.e("exception", e.toString());
									} catch (IOException e) {
										e.printStackTrace();
										Log.e("exception", e.toString());
									}
						    	}
						 }
						 if(fileIds!=null)
						 {
							 params.put("post.fileIds", fileIds.toString());
						 }
						HashMap res=  HttpUtil.postUrl4ResultMap(issurePostUrl,params);
						return res;
					} catch (ClientProtocolException e) {
						e.printStackTrace();
						return e;
					} catch (IOException e) {
						e.printStackTrace();
						return e;
					} catch (JSONException e) {
						e.printStackTrace();
						return e;
					}
	 				  
	    }
	    // @Override
//	     public void onProgressUpdate(Integer... args) {
//	    	 mLoadingDialog.setProgress(args[0]);
//	     }

	    @Override
	    protected void onPostExecute(Object result) {
	          if(result!=null &&	(result instanceof HashMap))
	          {
	        	HashMap mh =(HashMap)result;
	        	if(mh.get("code")!=null && "1".equals(mh.get("code"))){ 
//	        		Toast.makeText(ActivityTopicIssure.this, "发帖成功！",Toast.LENGTH_SHORT).show();            
	        		setResult(ActivityTopicReply.doReply);
					 dismissLoadingDialog();
					 finish();
	  			}else { 
	  				dismissLoadingDialog();
	  				Toast.makeText(ActivityTopicIssure.this, "处理失败！",Toast.LENGTH_SHORT).show();            
	  			} 
	          }else if(result instanceof Exception){ 
	        	  dismissLoadingDialog();
					Toast.makeText(ActivityTopicIssure.this, "处理失败！！",Toast.LENGTH_SHORT).show();            
			  } 
	    }
	    
	    private void dismissLoadingDialog() {
	   	 if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
	   		 mLoadingDialog.dismiss();
	   		 mLoadingDialog = null;
	   	 }
	    }
	}
	String filePath ;
	public void select_photo_from_dialog(){
		LayoutInflater inflater=ActivityTopicIssure.this.getLayoutInflater();
		View linearlayout= inflater.inflate(R.layout.carema_select_dialog, null);
		final Dialog	dialog	=	new AlertDialog.Builder(ActivityTopicIssure.this).setIcon(R.drawable.reg_personactivity_takephoto_icon_pressed)
				.setTitle("照片来源").setView(linearlayout).setItems(R.array.photo_select_from_items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    	if(which==0)
                    	{
                    		Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
                    		filePath = ParamUtil.getDatedFileName(Constants.SD_CARD_TEMP_DIR);
	          				i.putExtra(MediaStore.EXTRA_OUTPUT,
	          						Uri.fromFile(new File(filePath)));
	          				ActivityTopicIssure.this.startActivityForResult(i, Menu.FIRST);
	          				dialog.dismiss();
                    	}
                    	if(which==1){
                    		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            				intent.addCategory(Intent.CATEGORY_OPENABLE);
            				intent.setType("image/*");
            				intent.putExtra("return-data", true);
            				ActivityTopicIssure.this.startActivityForResult(intent, 5);
            				dialog.dismiss();
                    	}
                    }
                }).show();
	}
	ArrayList<String> photoPathList =new ArrayList();
	ArrayList<ImageView> photoPatObjhList =new ArrayList();
	HashMap params1 = new HashMap();
	StringBuffer fileIds = null;
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
if((requestCode==Menu.FIRST)||(requestCode==5)){
		if(requestCode==Menu.FIRST){
			if(filePath==null || data==null)
			{
				return ;
			}
			photoPathList.add(filePath);
		}else if(requestCode==5){
			if(data==null)
			{
				return ;
			}
			    ContentResolver resolver = getContentResolver();
			        try {
			            Uri originalUri = data.getData();  
			            Bitmap bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);        
			            String[] proj = {MediaStore.Images.Media.DATA};
			            Cursor cursor = managedQuery(originalUri, proj, null, null, null); 
			            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			            cursor.moveToFirst();
			            filePath = cursor.getString(column_index);
			            if(filePath==null)
			            {
			            	return ;
			            }
			            photoPathList.add(filePath);
			        }catch (IOException e) {
			        	
			        }
		}
		ImageView imageView = new ImageView(ActivityTopicIssure.this);
		imageView.setMaxHeight(65);
		imageView.setMaxWidth(50);
		imageView.setId(2012121011+photoPathList.size()-1);
		photoPatObjhList.add(imageView);
		 AppParam pdatabase=  AppParam.newInstance(ActivityTopicIssure.this);;
		 String reates =   pdatabase.get("carema.rsize");
		 int reate =0;
		 Bitmap cameraBitmap = null;
		 if(reates!=null)
		 {
			 reate=Integer.parseInt(reates);
		 }
			try {
				if(requestCode==5)
				{
					cameraBitmap = FileUtil.getImageBitmapAndResetRotate(filePath);
				}else{
					cameraBitmap = FileUtil.getImageBitmapAndSetRotate(filePath, reate);
				}
				Bitmap cameraBitmap2 =FileUtil.resizeBitmap(cameraBitmap,50,65);
				cameraBitmap.recycle();
				imageView.setImageBitmap(cameraBitmap2);
		} catch (IOException e) {
			e.printStackTrace();
		}
		params1.put("imageId",imageView.getId()+"");
		params1.put("isIssured","false");
		imageView.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Activity act = ActivityTopicIssure.this;
				int index = 0;
				String url =null;
				for(ImageView iv:photoPatObjhList)
				{
					if(iv.equals(v)){
						index = photoPatObjhList.indexOf(iv);
						url=photoPathList.get(index);
					}
				}
				params1.put("showImageurl",url);
				LayoutInflater inflater=act.getLayoutInflater();
				View linearlayout= inflater.inflate(R.layout.image_preview, null);
        		Dialog	dialog  =	new AlertDialog.Builder(act).setView(linearlayout).show();
        		WindowManager wm = (WindowManager) act.getSystemService(Context.WINDOW_SERVICE); 
        		final WebView  mWebView  = (WebView) linearlayout.findViewById(R.id.imagePreive_view); 
        		mWebView.setDrawingCacheEnabled(false);
        		mWebView.setInitialScale(100);//初始显示比例100%
        		 WebSettings webSettings = mWebView.getSettings(); 
                webSettings.setSavePassword(false);   
                webSettings.setSaveFormData(false);   
                webSettings.setJavaScriptEnabled(true);   
                webSettings.setSupportZoom(true);   
                webSettings.setBuiltInZoomControls(true);
                webSettings.setDatabaseEnabled(false);
                final int imageId = v.getId();
                webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
                mWebView.addJavascriptInterface(new AcceptReateRuesutl(), "image_rate_result");   
                ImageView  timg  = (ImageView) linearlayout.findViewById(R.id.image_turn); 
                timg.setOnClickListener(new OnClickListener(){
					public void onClick(View arg0) {
						 mWebView.loadUrl("javascript:timage()");
					}
                });
        		mWebView.setBackgroundColor(14737637);
        		params1.put("width", wm.getDefaultDisplay().getWidth()+"");
        		params1.put("height", wm.getDefaultDisplay().getHeight()*0.7+"");
        		String html=TopicList.createNew().compile(act,"image_preview.template", null,params1);
        		mWebView.loadDataWithBaseURL("file:///android_asset/.", html, "text/html", "utf-8", null);
        		dialog.setOnCancelListener(new OnCancelListener(){
					public void onCancel(DialogInterface arg0) {
					      		 if(reateMap.get(imageId)!=null)
					      		 {
				            		ImageView imageView  = (ImageView)findViewById(imageId);
				            		try {
				            			String url  = photoPathList.get(imageId-2012121011);
				            			Bitmap cameraBitmap = FileUtil.getImageBitmapAndSetRotate(url, reateMap.get(imageId));
				            			Bitmap cameraBitmap2 =FileUtil.resizeBitmap(cameraBitmap,50,65);
				            			imageView.setImageBitmap(cameraBitmap2);
				            			cameraBitmap.recycle();
				            			reateMap.remove(imageId);
									} catch (IOException e) {
										e.printStackTrace();
									}
					      		 }
					}
        		});
			}
		});
		layout.addView(imageView);
}
filePath=null;
	}
	private HashMap<Integer,Integer> reateMap  = new HashMap();
	 class AcceptReateRuesutl {
	        public void clickOnAndroid( int reageSize,int imageId) {   
	        	reateMap.put(imageId, reageSize);
	        }   
	}
	 
}
